package com.zlq.cn.service.lovers;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zlq.cn.bootstrap.SignApiBootstrap;
import com.zlq.cn.entity.LoversTime;
import com.zlq.cn.entity.User;
import com.zlq.cn.mapper.lovers.LoversTimeMapper;
import com.zlq.cn.service.un.UserService;
import one.util.streamex.StreamEx;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 小情侣-时光 服务实现类
 * </p>
 *
 * @author zhoucl
 * @since 2022-05-08
 */
@Service
public class LoversTimeService extends ServiceImpl<LoversTimeMapper, LoversTime> {

    @Resource
    private LoversBindUserService loversBindUserService;

    @Resource
    private UserService userService;

    public Page<LoversTime> pageLoversTime(Page<LoversTime> page) {
        User user = SignApiBootstrap.requestUser();
        Set<Integer> bindUserIds = loversBindUserService.getBindUserIds();
        bindUserIds.add(user.getId());
        super.lambdaQuery()
                .in(LoversTime::getUserId, bindUserIds)
                .page(page);
        List<LoversTime> records = page.getRecords();
        if (CollectionUtil.isNotEmpty(records)) {
            Map<Integer, User> userMap = StreamEx.of(records)
                    .map(LoversTime::getUserId)
                    .toListAndThen(userService::listByIds).stream()
                    .collect(Collectors.toMap(User::getId, Function.identity()));
            for (LoversTime record : records) {
                Optional.ofNullable(userMap.get(record.getUserId()))
                        .ifPresent(it -> {
                            record.setAvatar(it.getAvatar())
                                    .setUserName(it.getName());
                        });
            }
        }
        return page;
    }
}
